package com.jiazhong.example.project.shoppingcart.filter;

import com.jiazhong.example.project.shoppingcart.util.JsonResult;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter("/*")
public class IsLoginFilter extends HttpFilter {

    private List<String> urls;

    @Override
    public void init(FilterConfig config) throws ServletException {
        urls = new ArrayList<>();
        urls.add("carts");
    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("开始校验用户是否登陆");
        String uri = request.getRequestURI();
        System.out.println("用户访问的路径是：" + uri);
        boolean flag = false;
        for (String url : urls) {
            if (uri.contains(url)) {
                flag = true;
                break;
            }
        }
        System.out.println("flag:" + flag);
        if (!flag) {
            chain.doFilter(request, response);
            return;
        }
        Object user = request.getSession().getAttribute("user");
        System.out.println("用户登陆内容：" + user);
        if (user == null) {
            // response.sendRedirect("login.html?error=1");
            return ;
        }
        chain.doFilter(request, response);
    }
}
